<?php
namespace App\Models;
 class TxOrder extends BaseModel{
     protected $table = "tx_order";

     public function getOne($where, $fileds = '*', $order = '')
     {
         if (!$order) {
             $order = ['id' => 'desc'];
         }
         return $this->multiSelect($fileds)->multiWhere($where)->multiOrder($order)->first();
     }

     /**
      * 按条件查询全部数据,根据配置显示条数显示
      */
     public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
     {
         if ($pageSize) {
             return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
         } else {
             return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
         }
     }

     /**
      *插入数据
      */
     public function add($data)
     {
         return $this->_add($data);
     }


     /**
      *更新数据
      */
     public function up($where, $data)
     {
         //dd($this->multiWhere($where)->update($data));
         return $this->_updata($where, $data);
     }

     /**
      * @param $id
      * 删除数据
      */
     public function del($where)
     {
         return $this->_del($where);
     }

     /**
      * 获取提现列表
      */
     public function getOrderList(){
         $where['member_id'] = session('uid') ;
         $order = '';
         $rows = $this->getList($where, '*', $order, 3);
         if ($rows) {
             $rows = $rows->toArray();
             $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 10);
             return $rows;
         }
     }

     /**
      * 获取提现列表
      */
     public function getTxOrderList($request){
         $keyword = $request['keyword'] ? $request['keyword'] : '';
         $where = [];
         if ($keyword) {
             if (is_numeric($request['keywords'])) {
                 $where['tx_order_sn'] = $request['keywords'];
             } else {
                 //$where['pet_name'] = ['like', '%' . $request['keywords'] . '%'];
             }
         }
         $start = date("Y-m-d",strtotime($request['starttime']));
         $end = date("Y-m-d",strtotime($request['endtime']));
         $start1 = $start;
         $end1 = $end;
         if($start>$end){
             $start1 = $end;
             $end1 = $start;
         }

         if($request['starttime']&&$request['endtime']){
             $where['created_at'] = ['glt',[['>',$start1],['<=',$end1]]];
         }

         $order['id'] = 'desc';
         $rows = $this->getList($where, '*', $order, 10);
         if ($rows) {
             $rows = $rows->toArray();
             $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 10);
             return $rows;
         }
     }

     /**
      * 添加提现订单
      */
     public function addTxOrder($request){
          if(empty($request['txurl'])|| empty($request['num'])){
              $res = ['state'=>400,'msg'=>'提现地址或数量不能为空'];
              return $res;
          }

          // 判断提交的金额是否为数字
          if ( !is_numeric($request['num']) || !$request['num']<0) {
              $res = ['state'=>400,'msg'=>'请填写合法数量'];
              return $res;
          }

          $member = new Member();
          $memberInfo = $member->getMemberById(session('uid'));
          if($memberInfo['edu_amount']==0){
              $res = ['state'=>400,'msg'=>'金额不足'];
              return $res;
          }
          if($memberInfo['edu_amount']<$request['num']){
              $res = ['state'=>400,'msg'=>'金额不能大于已有金额'];
              
              return $res;
          }
          $data['tx_order_sn'] = $this->makePaySn(session('uid'));
          $data['tx_amount'] = $request['num'];
          $data['txurl'] = $request['txurl'];
          $data['member_id'] = 1;
          $data['tx_state'] = 0;
          $data['created_at'] = date("Y-m-d H:i:s",time());
          $data['updated_at'] = date("Y-m-d H:i:s",time());
          $this->start();
         try{
             $result = $this->add($data);
             if($result){
                 // 冻结提现金额
                 $updata['edu_amount'] = intval($memberInfo['edu_amount'])-intval($request['num']);
                 $updata['edu_freeze_amount'] = intval($memberInfo['edu_freeze_amount'])+intval($request['num']);
                 $res1 = $member->up(array('member_id'=>session('uid')),$updata);
                 if($res1){
                      $this->commit();
                      $res = ['state'=>200,'msg'=>'提现成功'];
                      return $res;
                 }else{
                     $this->rollBack();
                     $res = ['state'=>400,'msg'=>'提现失败'];
                     return $res;
                 }
             }
         } catch (\Exception $e){
             $this->rollBack();
             $res = ['state'=>400,'msg'=>'提现失败'];
             return $res;
         }
     }

     function getPageNoList($totalPage, $pageNo, $pageSize)
     {
         $disPageList = 0;//定义最大链接显示数额
         $disPageList = $pageNo + $pageSize - 1;//最大链接显示数额赋值，公式为"当前页数 + 最大链接显示数额 -1"
         //前页面导航页数
         $pageNoList = array();
         //循环显示出当前页面导航页数
         if ($disPageList <= $totalPage) {
             for ($i = $pageNo; $i <= $disPageList; $i++) {
                 $pageNoList[] = $i;
             }
         } else {
             if ($totalPage < $pageSize) {
                 for ($i = 1; $i <= $totalPage; $i++) {
                     $pageNoList[] = $i;
                 }
             } else {
                 $start = $totalPage - $pageSize + 1;
                 for ($i = $start; $i <= $totalPage; $i++) {
                     $pageNoList[] = $i;
                 }
             }
         }
         return $pageNoList;
     }

     /**
      * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
      * 长度 =2位 + 10位 + 3位 + 3位  = 18位
      * 1000个会员同一微秒提订单，重复机率为1/100
      * @return string
      */
     public function makePaySn($member_id) {
         return mt_rand(10,99)
         . sprintf('%010d',time() - 946656000)
         . sprintf('%03d', (float) microtime() * 1000)
         . sprintf('%03d', (int) $member_id % 1000);
     }

     /**
      *
      * 改变提现状态,提现审核
      *
      */
     public function changeTxStatus($request){


         $id = $request['id'];     //获取订单id
         $where['id'] = $id;
         $txinfo = $this->getOne($where);    //根据id获取该条订单详细信息

         if($txinfo['tx_state']!=0){   //如果表中字段不为0,则说明已经提现,无法再次提现
             $ajaxData['status'] = 0;
             $ajaxData['msg'] = '已确认过,无法重复提交';
             return $ajaxData;
         }


         $data['updated_at'] = date('Y-m-d H:i:s');

         //开启事务处理
         $this->start();

         try{

             //①更新提现状态

             $data['tx_state'] = 1;
             $res = $this->up($where, $data);    //更新tx_order表数据
             //dd(666);

             //②member表冻结资金清0


             $membermodel = new Member();
             $where2['id'] = $txinfo['member_id'];
             $membermodel->up($where2, array('edu_freeze_amount'=>0));     //提现表对应的那个用户的表

             //③充值日志
             $txinfo2 = $this->getOne($where);    //tx表更新后的信息
             $logmodel = new Log();   //实例化log模型用于调用addlog函数

             $logmodel->addLog($txinfo2,2);  //1 充值  2 提现

             $this->commit();


         }catch (\Exception $e){
             $this->rollBack();
             //echo $e->getMessage();die();
             $ajaxData['status'] = 0;
             $ajaxData['msg'] = '确认提现失败!';
             return $ajaxData;
         }


         $ajaxData['status'] = 1;
         $ajaxData['msg'] = '确认提现成功!';
         return $ajaxData;

     }


 }